package com.oyjd;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Match {
	private static String charset = "gb2312";

	/**
	 * @param args
	 * @throws Exception
	 */
	public static void main(String[] args) throws Exception {
		long begin = System.currentTimeMillis();
		String info="************************\r\nAuthor: 欧建东\r\nEmail: oyjd@163.com\r\nCreate Date: 2012-10-21\r\nUpdate Date: 2012-11-04\r\n************************";
		System.out.println(info);

		String basePath = "N:\\mystore\\CustMatch\\bin";
		if (null != args && args.length > 0) {
			basePath = args[0];
		}
		System.out.println("\r\n===================>获取设置根路径：" + basePath);
		if (new File(basePath).exists()) {
			String outPath = basePath + "\\result";
			new File(outPath).mkdirs();
			System.out.println("------->分配内存空间");
			Map<String, String> aim = new HashMap<String, String>(1000000);
			File faim = new File(basePath + "\\aim");
			for (File f : faim.listFiles()) {
				if (!f.isFile() || !f.getName().endsWith("csv")) {
					continue;
				}
				System.out.println("------->正在读取客户目标文件：" + f.getPath());
				fillAimList(aim, f);
			}
			System.out.println("------------------------------------------------------------------------------------------------\r\n");

			File saim = new File(basePath + "\\sou");
			for (File f : saim.listFiles()) {
				if (!f.isFile() || !f.getName().endsWith("csv")) {
					continue;
				}

				System.out.println("------->分配内存空间");
				Map<String, List<String>> map = new HashMap<String, List<String>>(2000000);
				List<String> result = new ArrayList<String>(10000);
				List<String> matchKey = new ArrayList<String>(10000);
				List<String> disMatchKey = new ArrayList<String>(500000);
				System.out.println("------->正在读取渠道CSV文件：" + f.getPath());
				TmpVO tmpVO = fillSouMap(map, f);
				System.out.println("------->正在进行匹配...");
				for (String key : aim.keySet()) {
					if (map.containsKey(key)) {
						matchKey.add(key);
						result.addAll(map.get(key));
					} else {
						disMatchKey.add(key);
					}
				}

				// 结果输出
				String name = f.getName().substring(0, f.getName().lastIndexOf("."));
				StringBuffer sb = new StringBuffer();
				DecimalFormat df = new DecimalFormat("#.00");
				double n1 = matchKey.size() * 100d / aim.size();
				double n2 = result.size() * 100d / tmpVO.getCount();
				sb.append("渠道文件：").append(f.getName()).append("\r\n");
				sb.append("-----------------------\r\n");
				sb.append("渠道信息总条数：").append(tmpVO.getCount()).append("\r\n");
				sb.append("任务号码总数：").append(aim.size()).append("\r\n");
				sb.append("-----------------------\r\n");
				sb.append("匹配号码数：").append(matchKey.size()).append("\r\n");
				sb.append("未匹配号码数：").append(disMatchKey.size()).append("\r\n");
				sb.append("匹配结果数：").append(result.size()).append("\r\n");
				sb.append("-----------------------\r\n");
				sb.append("任务号码匹配率：").append(matchKey.size() + "/" + aim.size() + "=" + df.format(n1) + "%").append("\r\n");
				sb.append("渠道信息配率：").append(result.size() + "/" + tmpVO.getCount() + "=" + df.format(n2) + "%").append("\r\n");
				sb.append("\r\n\r\n");
				sb.append(info);

				writeFile(matchKey, outPath + "\\" + name + "_匹配号码.csv", "手机号码");
				writeFile(disMatchKey, outPath + "\\" + name + "_未匹配号码.csv", "手机号码");
				writeFile(result, outPath + "\\" + name + "_匹配结果.csv", tmpVO.getHead());
				writeFile(outPath + "\\" + name + "_统计信息.txt", sb.toString(), charset);

				System.out.println("------------------------------------------------------------------------------------------------\r\n");
			}
		} else {
			System.out.println("===================>根路径：" + basePath + "不存在！\r\n");
		}
		System.out.println("===================>共耗时：" + ((System.currentTimeMillis() - begin) / 1000) + "秒\r\n");
		System.out.println("**********程序结束**********");
	}

	/**
	 * 读取目标客户
	 * 
	 * @param aim
	 * @param path
	 * @throws Exception
	 */
	private static void fillAimList(Map<String, String> aim, File path) throws Exception {
		BufferedReader dr = new BufferedReader(new InputStreamReader(new FileInputStream(path), charset));
		int count = 0;
		String line;
		while (null != (line = dr.readLine())) {
			if (!"".equals(line)) {
				String[] s = line.split(",");
				String num = s[0].replaceAll("\"", "");
				// System.out.println(num);
				if (!aim.containsKey(num)) {
					aim.put(num, "");
				}
				count++;
			}
		}
		System.out.println("------->读取条数：" + count);
		dr.close();
	}

	/**
	 * 读取渠道文件
	 * 
	 * @param aim
	 * @param path
	 * @throws Exception
	 */
	private static TmpVO fillSouMap(Map<String, List<String>> map, File file) throws Exception {
		int count = 0;
		int phonePos = -1;
		if (-1 != file.getName().indexOf("腾讯")) {
			phonePos = 0;
		} else if (-1 != file.getName().indexOf("新浪")) {
			phonePos = 1;
		} else if (-1 != file.getName().indexOf("微信")) {
			phonePos = 0;
		}

		// 比较源数据
		BufferedReader dr = new BufferedReader(new InputStreamReader(new FileInputStream(file), charset));
		String head = null;
		String line;
		while (null != (line = dr.readLine())) {
			if (!"".equals(line)) {
				if (null == head) {
					head = line;
				} else {
					String[] s = line.split(",");
					String key = s[phonePos];
					if (map.containsKey(key)) {
						map.get(key).add(line);
					} else {
						List<String> tmp = new ArrayList<String>();
						tmp.add(line);
						map.put(key, tmp);
					}
					count++;
				}
			}
		}
		System.out.println("------->读取条数：" + count);
		dr.close();
		return new TmpVO(count, head);
	}

	/**
	 * 写入文件
	 * 
	 * @param sou
	 * @param file
	 */
	private static void writeFile(List<String> sou, String file, String head) {
		StringBuffer sb = new StringBuffer(head + "\r\n");
		for (String s : sou) {
			sb.append(s).append("\r\n");
		}
		writeFile(file, sb.toString(), charset);
	}

	/**
	 * 写入文件
	 * 
	 * @param path
	 *            路径
	 * @param content
	 *            文件字符内容
	 * @param encoding
	 *            文件编码
	 */
	private static void writeFile(String path, String content, String encoding) {
		try {
			File f = new File(path);
			f.getParentFile().mkdirs();
			byte[] all = content.getBytes(encoding);
			FileOutputStream fos = new FileOutputStream(f);
			fos.write(all);
			fos.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("------->输出文件：" + path);
	}

}

class TmpVO {
	private int count;
	private String head;

	public TmpVO(int count, String head) {
		super();
		this.count = count;
		this.head = head;
	}

	public int getCount() {
		return count;
	}

	public void setCount(int count) {
		this.count = count;
	}

	public String getHead() {
		return head;
	}

	public void setHead(String head) {
		this.head = head;
	}
}
